import React, { useState } from "react";
import { getUserLogin, getsms, userregister } from '../../api/user'
import { connect } from "react-redux";
import { SAGA_ADMIN_INFO, SAGA_LOGIN_STATE } from "../../store/type";
//组件
import { Button, Checkbox, Form, Input, message, Modal, Select, Col, Row, } from 'antd';
//组件图标
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from "react-router";
import './index.scss'

const { Option } = Select;

const App = ({ setAdminInfo }) => {
    const [messageApi, contextHolder] = message.useMessage();
    // 创建一个路由方法
    const navigate = useNavigate()

    // 点击 登录按钮, 并且 数据通过 form 表单的验证后, 执行
    const onFinish = (values) => {
        // 因为 用户名和密码, 以及 打开用户提示的 messageApi 都只在 App 函数中能用, 所以需要将数据通过参数的方式, 传递给 setAdminInfo, 否在无法在内部使用
        setAdminInfo(values, messageApi).then((res) => {
            navigate('/');
        });
    }

    // 控制修改密码的对话框
    const [isModalOpen, setIsModalOpen] = useState(false);

    // --------------注册相关-----------------------------------------------------
    const [sms, setsms] = useState('')
    const [confirmPw, setConfirmPw] = useState('')
    // 存放用户注册时信息的状态数据
    const [userInfo, setUserInfo] = useState({})
    // 获取验证码函数
    const getSmsFunction = () => {
        getsms({ username: userInfo.username }).then((res) => {
            console.log(res.data);
            if (res.data.code !== "200") {
                return messageApi.open({
                    type: "error",
                    content: res.data.message,
                });
            }
            window.localStorage.setItem('sms', res.data.sms)
        })
    }

    // 注册按钮
    const registerFn = () => {
        if (sms !== window.localStorage.getItem('sms')) return messageApi.open({ content: '验证码不正确' });
        if (confirmPw !== userInfo.password) return messageApi.open({ content: '两次密码输入不一致确' })

        userregister({
            username: userInfo.username,
            password: userInfo.password,
            phone: userInfo.username,
            id: '10087'

        }).then(res => {
            console.log(res.data);
            if (res.data.code === '200') {
                messageApi.open({
                    content: res.data.message,
                    type: "success",
                });
            }
        })

        setUserInfo({})
        window.localStorage.clear()
        setIsModalOpen(false)
    }

    return (
        <div className="boxbj">
            {/* message 提示信息, 必须书写的一个内容 */}
            {contextHolder}
            {/* 修改密码的对话框 */}
            <Modal
                title="注册账号"
                open={isModalOpen}
                // onOk={() => {
                //     setUserInfo({})
                //     window.localStorage.clear()
                //     setIsModalOpen(false)
                // }}
                onCancel={() => { setIsModalOpen(false) }}
                // cancelText='取消'
                // okText='确认'
                footer={null}
            >

                {/* 手机号/用户名 */}
                <Form.Item
                    name="username"
                    label="手机号/用户名 "
                >
                    <Input
                        style={{ width: '100%' }}
                        value={userInfo.username}
                        onChange={(e) => {
                            // console.log(e.target.value);
                            setUserInfo({
                                ...userInfo,
                                username: e.target.value
                            })
                        }}
                    />
                </Form.Item>
                {/* 验证码 */}
                <Form.Item label="验证码" >
                    <Row gutter={8}>
                        <Col span={12}>
                            <Form.Item
                                name="captcha"
                                noStyle
                            >
                                <Input value={userInfo.sms} onChange={(e) => {
                                    setsms(e.target.value)
                                }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Button
                                onClick={getSmsFunction}
                            >获取验证码</Button>
                        </Col>
                    </Row>
                </Form.Item>

                {/* 密码 */}
                <Form.Item
                    name="password"
                    label="密码"
                    hasFeedback
                >
                    <Input.Password
                        value={userInfo.password}
                        onChange={(e) => {
                            // console.log(e.target.value);
                            setUserInfo({
                                ...userInfo,
                                password: e.target.value
                            })
                        }} />
                </Form.Item>
                {/* 确认密码 */}
                <Form.Item
                    name="confirm"
                    label="确认密码"
                    dependencies={['password']}
                    hasFeedback

                >
                    <Input.Password
                        value={confirmPw}
                        onChange={(e) => {
                            setConfirmPw(e.target.value)
                        }}
                    />
                </Form.Item>
                <Button
                    onClick={registerFn}
                >注册</Button>

            </Modal>

            {/* 登陆输入框表单 */}
           <div className="loginForm">
           <Form
                name="normal_login"
                className="login-form"
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
            >欢迎来到嗨课堂！
                <Form.Item
                    name="username"
                    rules={[
                        {
                            required: true,
                            message: '请输入用户名',
                        },
                    ]}

                >
                    <Input
                        prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名"
                        style={{
                            width: 200
                        }}
                    />
                </Form.Item>
                <Form.Item
                    name="password"
                    rules={[
                        {
                            required: true,
                            message: '请输入密码',
                        },
                    ]}
                >
                    <Input
                        prefix={<LockOutlined className="site-form-item-icon" />}
                        type="password"
                        placeholder="请输入密码"
                        style={{
                            width: 200
                        }}
                    />
                </Form.Item>
                <Form.Item>
                    <Form.Item name="remember" valuePropName="checked" noStyle>
                        <Checkbox>记住密码</Checkbox>
                    </Form.Item>

                    {/* <span
                        className="login-form-forgot"
                        onClick={() => { setIsModalOpen(true) }}
                    >
                        忘记密码
                    </span> */}
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        登录
                    </Button>  &nbsp;&nbsp;&nbsp;&nbsp;
                    <a onClick={() => { setIsModalOpen(true) }}>注册</a>
                </Form.Item>
            </Form>
           </div>
        </div>
    );
};

const mapDispatchToprops = (dispatch) => ({
    setAdminInfo(values, messageApi) {
        return new Promise((result) => {

            //返回promise对象
            // 1.发请求
            getUserLogin({
                username: values.username,
                password: values.password,
            }).then((res) => {
                console.log(res.data);
                //2.1提示用户是否登录成功
                if (res.data.code !== "200") {
                    return messageApi.open({
                        type: 'error',
                        content: res.data.message,
                    });
                }
                console.log(res.data);
                messageApi.open({
                    type: 'susscess',
                    content: '登录成功',
                });
                // 2.2请求成功，储存数据
                dispatch({
                    type: SAGA_ADMIN_INFO,
                    payload: res.data,
                });
                dispatch({
                    type: SAGA_LOGIN_STATE,
                    payload: true,
                });
                // 2.3将当前的promise状态修改为成功
                result();
            })

        })
    }
})

export default connect(null, mapDispatchToprops)(App);